import { useState, useEffect, useRef } from 'react';

type Props = {
  countDown?: string,
  createTime?: number,
}

export const CountDown = (props: Props) => {
  const { countDown, createTime } = props;
  const timer = useRef<any>(null);
  const [ctime, setCtime] = useState<string>('');
  const [time, setTime] = useState<string>('');

  const formatTime = (n: number) => { // 格式化时间的函数
    if (isNaN(n)) { // 如果输入的时间戳为 NaN，则返回空字符串
      return '';
    }
    const date = new Date(n);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    const hour = ('0' + date.getHours()).slice(-2);
    const minute = ('0' + date.getMinutes()).slice(-2);
    const second = ('0' + date.getSeconds()).slice(-2);
    const formattedTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    setCtime(formattedTime);
    return formattedTime;
  }

  const dealData = () => {
    const endTime = new Date(countDown)
    const now = new Date();
    const diff = Math.floor(endTime.getTime() - now.getTime() / 1000)
    if (diff <= 0) {
      setTime('');
      return timer.current && clearTimeout(timer.current);
    }
    const h = parseInt(((diff / (60 * 60)) % 24) + '');
    const m = parseInt(((diff / 60) % 60) + '');
    const s = parseInt((diff % 60) + '');
    setTime(`${h}时${m}分${s}秒`);
    timer.current = setTimeout(() => {
      dealData();
    }, 1000);
  };

  useEffect(() => {
    dealData();
    return () => {
      timer.current && clearTimeout(timer.current);
    }
  }, []);

  useEffect(()=>{
    formatTime(createTime)
  },[createTime])

  return (
    <>
      {countDown  && <span>{time}</span>}
      {createTime && <span>{ctime}</span>}
    </>
  );
};
